<?php
/**
*	WebSocket
*/
namespace Rainrock\Framework\kernel\socket;


use Rainrock\Framework\kernel\base\Base;
use Rainrock\Framework\kernel\base\CLog;

class WebSocket{
	
	/**
	*	默认的端口
	*/
	private $port = 6556;
	
	
	private $sbool = true;
	
	
	public function __construct()
	{
		$port = Base::getConfig('websocket_port');
		if($port)$this->port = $port;
	}
	
	/**
	*	启动
	*/
	public function start()
	{
		$server = stream_socket_server('tcp://0.0.0.0:'.$this->port.'', $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);
		if (!$server) {
			CLog::error("Oops! Failed to create socket: $errstr ($errno)");
			return;
		}
		CLog::show('['.getmypid().']websocket(http://127.0.0.1:'.$this->port.') start success');
		
		//stream_set_blocking($server, false); //非阻塞
		
		while($this->sbool) {
			$client = @stream_socket_accept($server);
			if($client){
				$this->clientConnection($client);// 处理客户端连接
			}
			
		}
		
		fclose($socket);
	}
	
	/**
	*	停止
	*/
	public function stop()
	{
		
	}
	
	private function clientConnection($client)
	{
		//stream_set_blocking($client, false);
		new WebSocket_Client($client);
	}
}